<template>
	<view class="merchant-detail">
		<!-- 导航栏 -->
		<u-navbar :title="merchantInfo.name || '商家详情'" :border-bottom="false" :background="{ backgroundColor: '#fff' }">
			<template #left>
				<u-icon name="arrow-left" size="20" @click="goBack"></u-icon>
			</template>
			<template #right>
				<u-icon name="share" size="20" @click="shareMerchant"></u-icon>
			</template>
		</u-navbar>
		
		<!-- 商家信息 -->
		<view class="merchant-header">
			<image :src="merchantInfo.cover_image" class="merchant-cover"></image>
			<view class="merchant-info">
				<view class="info-top">
					<image :src="merchantInfo.logo" class="merchant-logo"></image>
					<view class="basic-info">
						<text class="merchant-name">{{ merchantInfo.name }}</text>
						<view class="merchant-rating">
							<view class="stars">
								<text v-for="i in 5" :key="i" class="star" :class="{ filled: i <= merchantInfo.rating }">★</text>
							</view>
							<text class="rating-text">{{ merchantInfo.rating }}</text>
							<text class="review-count">({{ merchantInfo.review_count }}条评价)</text>
						</view>
					</view>
				</view>
				
				<view class="merchant-tags">
					<text v-for="tag in merchantInfo.tags" :key="tag" class="tag">{{ tag }}</text>
				</view>
				
				<view class="delivery-info">
					<text class="info-item">📍 {{ merchantInfo.distance }}</text>
					<text class="info-item">⏰ {{ merchantInfo.delivery_time }}</text>
					<text class="info-item">💰 配送费¥{{ merchantInfo.delivery_fee }}</text>
				</view>
				
				<view v-if="merchantInfo.promotion" class="promotion">
					<text class="promotion-text">{{ merchantInfo.promotion }}</text>
				</view>
			</view>
		</view>
		
		<!-- 商品分类导航 -->
		<view class="category-nav">
			<scroll-view scroll-x class="category-scroll">
				<view 
					v-for="(category, index) in goodsCategories" 
					:key="category.id"
					@click="selectGoodsCategory(category, index)"
					class="category-item"
					:class="{ active: selectedCategoryIndex === index }"
				>
					<text class="category-name">{{ category.name }}</text>
				</view>
			</scroll-view>
		</view>
		
		<!-- 商品列表 -->
		<view class="goods-list">
			<view v-if="loading" class="loading-container">
				<u-loading-icon></u-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>
			
			<view v-else-if="filteredGoods.length === 0" class="empty-container">
				<u-empty text="暂无商品" mode="data"></u-empty>
			</view>
			
			<view v-else>
				<view 
					v-for="goods in filteredGoods" 
					:key="goods.id" 
					class="goods-item"
				>
					<image :src="goods.image" class="goods-image" @click="viewGoods(goods)"></image>
					<view class="goods-info">
						<text class="goods-name" @click="viewGoods(goods)">{{ goods.name }}</text>
						<text class="goods-desc">{{ goods.description }}</text>
						<view class="goods-stats">
							<text class="sales-count">月销{{ goods.sales_count }}</text>
							<text class="like-rate">好评率{{ goods.like_rate }}%</text>
						</view>
						<view class="price-section">
							<text class="current-price">¥{{ goods.price }}</text>
							<text v-if="goods.original_price" class="original-price">¥{{ goods.original_price }}</text>
						</view>
					</view>
					<view class="goods-actions">
						<view class="quantity-control" v-if="getCartQuantity(goods.id) > 0">
							<button class="quantity-btn" @click="decreaseQuantity(goods)">-</button>
							<text class="quantity-text">{{ getCartQuantity(goods.id) }}</text>
							<button class="quantity-btn" @click="increaseQuantity(goods)">+</button>
						</view>
						<button v-else class="add-cart-btn" @click="addToCart(goods)">+</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 购物车悬浮按钮 -->
		<view class="cart-float" v-if="cartTotalQuantity > 0" @click="showCart">
			<view class="cart-icon">
				<u-icon name="shopping-cart" size="24" color="#fff"></u-icon>
				<view class="cart-badge">{{ cartTotalQuantity }}</view>
			</view>
			<view class="cart-info">
				<text class="cart-total">¥{{ cartTotalPrice }}</text>
				<text class="delivery-tip">另需配送费¥{{ merchantInfo.delivery_fee }}</text>
			</view>
			<button class="checkout-btn" @click="checkout">去结算</button>
		</view>
		
		<!-- 购物车弹窗 -->
		<u-popup v-model="showCartModal" mode="bottom" border-radius="20">
			<view class="cart-modal">
				<view class="cart-header">
					<text class="cart-title">购物车</text>
					<text class="clear-cart" @click="clearCart">清空</text>
				</view>
				<view class="cart-list">
					<view v-for="item in cartItems" :key="item.id" class="cart-item">
						<image :src="item.image" class="item-image"></image>
						<view class="item-info">
							<text class="item-name">{{ item.name }}</text>
							<text class="item-price">¥{{ item.price }}</text>
						</view>
						<view class="item-quantity">
							<button class="quantity-btn" @click="decreaseQuantity(item)">-</button>
							<text class="quantity-text">{{ item.quantity }}</text>
							<button class="quantity-btn" @click="increaseQuantity(item)">+</button>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import api from '@/api/index.js'

export default {
	data() {
		return {
			merchantId: '',
			merchantInfo: {},
			goodsCategories: [],
			goodsList: [],
			selectedCategoryIndex: 0,
			cartItems: [],
			showCartModal: false,
			loading: false
		}
	},
	
	computed: {
		// 根据选中分类筛选商品
		filteredGoods() {
			if (this.selectedCategoryIndex === 0) {
				return this.goodsList
			}
			
			const selectedCategory = this.goodsCategories[this.selectedCategoryIndex]
			return this.goodsList.filter(goods => goods.category_id === selectedCategory.id)
		},
		
		// 购物车总数量
		cartTotalQuantity() {
			return this.cartItems.reduce((total, item) => total + item.quantity, 0)
		},
		
		// 购物车总价格
		cartTotalPrice() {
			return this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0).toFixed(2)
		}
	},
	
	onLoad(options) {
		if (options.id) {
			this.merchantId = options.id
			this.loadMerchantInfo()
			this.loadGoodsCategories()
			this.loadGoodsList()
		}
	},
	
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 分享商家
		shareMerchant() {
			uni.showShareMenu({
				title: this.merchantInfo.name,
				path: `/pages/merchant/detail?id=${this.merchantId}`
			})
		},
		
		// 加载商家信息
		async loadMerchantInfo() {
			try {
				const res = await api.o2oApi.getMerchantDetail(this.merchantId)
				if (res.r === 0) {
					this.merchantInfo = res.data
				}
			} catch (error) {
				console.error('加载商家信息失败:', error)
			}
		},
		
		// 加载商品分类
		async loadGoodsCategories() {
			try {
				const res = await api.o2oApi.getGoodsCategories(this.merchantId)
				if (res.r === 0) {
					this.goodsCategories = [{ id: 0, name: '全部' }, ...(res.data.list || [])]
				}
			} catch (error) {
				console.error('加载商品分类失败:', error)
			}
		},
		
		// 加载商品列表
		async loadGoodsList() {
			if (this.loading) return
			
			this.loading = true
			
			try {
				const res = await api.o2oApi.getMerchantGoods(this.merchantId)
				if (res.r === 0) {
					this.goodsList = res.data.list || []
				}
			} catch (error) {
				console.error('加载商品列表失败:', error)
			} finally {
				this.loading = false
			}
		},
		
		// 选择商品分类
		selectGoodsCategory(category, index) {
			this.selectedCategoryIndex = index
		},
		
		// 查看商品详情
		viewGoods(goods) {
			uni.navigateTo({
				url: `/pages/goods/detail?id=${goods.id}&merchant_id=${this.merchantId}`
			})
		},
		
		// 获取购物车中商品数量
		getCartQuantity(goodsId) {
			const item = this.cartItems.find(item => item.id === goodsId)
			return item ? item.quantity : 0
		},
		
		// 添加到购物车
		addToCart(goods) {
			const existingItem = this.cartItems.find(item => item.id === goods.id)
			
			if (existingItem) {
				existingItem.quantity++
			} else {
				this.cartItems.push({
					id: goods.id,
					name: goods.name,
					image: goods.image,
					price: goods.price,
					quantity: 1
				})
			}
			
			uni.showToast({
				title: '已添加到购物车',
				icon: 'success',
				duration: 1000
			})
		},
		
		// 增加数量
		increaseQuantity(goods) {
			const item = this.cartItems.find(item => item.id === goods.id)
			if (item) {
				item.quantity++
			} else {
				this.addToCart(goods)
			}
		},
		
		// 减少数量
		decreaseQuantity(goods) {
			const itemIndex = this.cartItems.findIndex(item => item.id === goods.id)
			if (itemIndex > -1) {
				const item = this.cartItems[itemIndex]
				if (item.quantity > 1) {
					item.quantity--
				} else {
					this.cartItems.splice(itemIndex, 1)
				}
			}
		},
		
		// 显示购物车
		showCart() {
			this.showCartModal = true
		},
		
		// 清空购物车
		clearCart() {
			uni.showModal({
				title: '确认清空',
				content: '确定要清空购物车吗？',
				success: (res) => {
					if (res.confirm) {
						this.cartItems = []
						this.showCartModal = false
					}
				}
			})
		},
		
		// 去结算
		checkout() {
			if (this.cartItems.length === 0) {
				uni.showToast({
					title: '购物车为空',
					icon: 'none'
				})
				return
			}
			
			// 跳转到订单确认页面
			uni.navigateTo({
				url: `/pages/order/confirm?type=o2o&merchant_id=${this.merchantId}&cart_data=${encodeURIComponent(JSON.stringify(this.cartItems))}`
			})
		}
	}
}
</script>

<style scoped>
.merchant-detail {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

/* 商家头部信息 */
.merchant-header {
	position: relative;
	margin-bottom: 20rpx;
}

.merchant-cover {
	width: 100%;
	height: 300rpx;
	object-fit: cover;
}

.merchant-info {
	background-color: #fff;
	padding: 30rpx;
	margin-top: -60rpx;
	border-radius: 20rpx 20rpx 0 0;
	position: relative;
	z-index: 1;
}

.info-top {
	display: flex;
	align-items: flex-start;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.merchant-logo {
	width: 120rpx;
	height: 120rpx;
	border-radius: 16rpx;
	object-fit: cover;
	border: 4rpx solid #fff;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.basic-info {
	flex: 1;
}

.merchant-name {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
	display: block;
}

.merchant-rating {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.stars {
	display: flex;
	gap: 2rpx;
}

.star {
	font-size: 24rpx;
	color: #ddd;
}

.star.filled {
	color: #ffa500;
}

.rating-text {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.review-count {
	font-size: 24rpx;
	color: #999;
}

.merchant-tags {
	display: flex;
	gap: 10rpx;
	margin-bottom: 20rpx;
	flex-wrap: wrap;
}

.tag {
	padding: 8rpx 16rpx;
	background-color: #f0f0f0;
	border-radius: 20rpx;
	font-size: 24rpx;
	color: #666;
}

.delivery-info {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
	flex-wrap: wrap;
}

.info-item {
	font-size: 26rpx;
	color: #666;
}

.promotion {
	padding: 16rpx;
	background: linear-gradient(135deg, #ff6b6b, #ffa500);
	border-radius: 12rpx;
}

.promotion-text {
	font-size: 26rpx;
	color: #fff;
	font-weight: bold;
}

/* 商品分类导航 */
.category-nav {
	background-color: #fff;
	padding: 20rpx 0;
	margin-bottom: 20rpx;
}

.category-scroll {
	white-space: nowrap;
}

.category-item {
	display: inline-block;
	padding: 16rpx 30rpx;
	margin: 0 10rpx;
	border-radius: 30rpx;
	transition: all 0.3s;
}

.category-item.active {
	background-color: #667eea;
	color: #fff;
}

.category-name {
	font-size: 28rpx;
	color: #333;
}

.category-item.active .category-name {
	color: #fff;
}

/* 商品列表 */
.goods-list {
	padding: 0 20rpx;
}

.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 60rpx 0;
	gap: 20rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}

.empty-container {
	padding: 60rpx 0;
}

.goods-item {
	display: flex;
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.goods-image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 12rpx;
	object-fit: cover;
	margin-right: 20rpx;
}

.goods-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.goods-name {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 8rpx;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.goods-desc {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 12rpx;
	display: -webkit-box;
	-webkit-line-clamp: 1;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.goods-stats {
	display: flex;
	gap: 20rpx;
	margin-bottom: 12rpx;
}

.sales-count,
.like-rate {
	font-size: 22rpx;
	color: #999;
}

.price-section {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.current-price {
	font-size: 32rpx;
	font-weight: bold;
	color: #ff4d4f;
}

.original-price {
	font-size: 24rpx;
	color: #999;
	text-decoration: line-through;
}

.goods-actions {
	display: flex;
	align-items: flex-end;
	margin-left: 20rpx;
}

.quantity-control {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	border: 2rpx solid #667eea;
	background-color: #fff;
	color: #667eea;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.quantity-text {
	font-size: 28rpx;
	color: #333;
	min-width: 40rpx;
	text-align: center;
}

.add-cart-btn {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	background-color: #667eea;
	color: #fff;
	font-size: 32rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 购物车悬浮按钮 */
.cart-float {
	position: fixed;
	bottom: 20rpx;
	left: 20rpx;
	right: 20rpx;
	height: 100rpx;
	background-color: #667eea;
	border-radius: 50rpx;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	box-shadow: 0 8rpx 30rpx rgba(102, 126, 234, 0.3);
	z-index: 100;
}

.cart-icon {
	position: relative;
	margin-right: 20rpx;
}

.cart-badge {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	width: 36rpx;
	height: 36rpx;
	background-color: #ff4d4f;
	border-radius: 50%;
	color: #fff;
	font-size: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.cart-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.cart-total {
	font-size: 32rpx;
	font-weight: bold;
	color: #fff;
}

.delivery-tip {
	font-size: 22rpx;
	color: rgba(255, 255, 255, 0.8);
}

.checkout-btn {
	padding: 20rpx 40rpx;
	background-color: #fff;
	color: #667eea;
	border-radius: 30rpx;
	font-size: 28rpx;
	font-weight: bold;
	border: none;
}

/* 购物车弹窗 */
.cart-modal {
	max-height: 60vh;
	padding: 30rpx;
}

.cart-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
	padding-bottom: 20rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.cart-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.clear-cart {
	font-size: 28rpx;
	color: #999;
}

.cart-list {
	max-height: 40vh;
	overflow-y: auto;
}

.cart-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 2rpx solid #f0f0f0;
}

.cart-item:last-child {
	border-bottom: none;
}

.item-image {
	width: 100rpx;
	height: 100rpx;
	border-radius: 12rpx;
	object-fit: cover;
	margin-right: 20rpx;
}

.item-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.item-name {
	font-size: 28rpx;
	color: #333;
}

.item-price {
	font-size: 26rpx;
	color: #ff4d4f;
	font-weight: bold;
}

.item-quantity {
	display: flex;
	align-items: center;
	gap: 10rpx;
}
</style>